package com.chixing.util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * 该类用于获得SqlSession 与 关闭sqlSession的
 *
 * SqlSession： 用于执行SQL语句
 * （1）内部封装了 PreparedStatement
 * （2）一级缓存
 *
 *
 * sqlSessionFactory: 重量级
 */
public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory ;
    private static  SqlSession sqlSession ;
    static{
        InputStream is = MybatisUtil.class.getResourceAsStream("/config/mybatis-config.xml");// 加载并读取 config/mybatis-config.xml
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    }


    public static SqlSession getSqlSession(){
        sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }

    public static  void closeSqlSession(){
        if(sqlSession != null)
            sqlSession.close();
    }
}
